package com.zhenyi.dingke.index;

import java.util.Date;
import java.util.List;

import org.joda.time.DateTime;

import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.utils.AESUtils;
import com.utils.AuthUtils;
import com.utils.DateUtils;
import com.zhenyi.dingke.interceptor.DKAuthIntercetpor;
import com.zhenyitech.common.model.DkArrange;
import com.zhenyitech.common.model.DkArrangeUser;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;

@Before(DKAuthIntercetpor.class)
public class DKHomeController extends DKController {

	@Clear
	public void login() {
		String key = RandomUtil.randomString(16);
		setAttr("key", key);
		setSessionAttr("key", key);
		render("/dk/admin/login.html");
	}

	@Clear
	public void auth() {
		String account = getPara("account");
		String password = getPara("password");
		try {
			String key = getSessionAttr("key");
			password = AESUtils.decrypt(key, password);
			if (password == null) {
				renderFailure();
				return;
			}
			if (!"lantian".equals(account)) {
				renderFailure("账号/密码错误 错误代码:100501");
				return;
			}
			if (!"lantian".equals(password)) {
				renderFailure("账号/密码错误 错误代码:100501");
				return;
			}
			String redirectUrl = "/dk/admin/list";
			renderSuccess(redirectUrl);
			AuthUtils.login("lantian", this);
		} catch (Exception e) {
			e.printStackTrace();
			renderFailure("账号/密码错误 错误代码:100500");
		}
	}

	@Override
	public void list() {
		String startDate = getPara("startDate", DateUtil.today() + " 00:00:00");
		String endDate = getPara("endDate");
		if (StrKit.isBlank(endDate)) {
			Date dt = new DateTime().plusDays(7).toDate();
			String str = DateUtil.format(dt, DateUtils.YYYYMMDD) + " 23:59:59";
			endDate = str;
		}
		Kv kv = Kv.create();
		kv.set("startTime", startDate);
		kv.set("endTime", endDate);
		setAttr("startTime", startDate);
		setAttr("endTime", endDate);
		SqlPara sqlPara = db.getSqlPara("DKArranges", kv);
		Page<Record> pages = db.paginate(getPage(), PAGE_SIZE, sqlPara);
		setRainbow(pages);
		setItems(JsonKit.toJson(pages.getList()));
		render("/dk/admin/arrange/list.html");
	}

	@Override
	public void info() {
		Long arrangeId = getParaToLong("arrangeId");
		DkArrange arrange;
		if (arrangeId == null) {
			arrange = new DkArrange();
		} else {
			arrange = DkArrange.dao.findById(arrangeId);
		}
		if (arrange.getStartTime() != null) {
			arrange.put("date", DateUtil.format(arrange.getStartTime(), "yyyy-MM-dd"));
			arrange.set("startTime", DateUtil.format(arrange.getStartTime(), "HH:mm"));
			arrange.set("endTime", DateUtil.format(arrange.getEndTime(), "HH:mm"));
		}
		// setInfoItem(arrange);
		setInfoItem(JsonKit.toJson(arrange));
		render("/dk/admin/arrange/info.html");
	}

	@Override
	public void submit() {
		Long arrangeId = getParaToLong("arrangeId");
		// Long courseId = getParaToLong("courseId");
		String courseName = getPara("courseName");
		String teacherName = getPara("teacherName");
		// if (courseId == null) {
		// renderFailure("请选择课程");
		// return;
		// }
		// Long staffId = getParaToLong("staffId");
		String date = getPara("date");
		if (StrKit.isBlank(date)) {
			renderFailure("请选择日期");
			return;
		}
		String startTime = getPara("startTime", "09:00");
		Date start = DateUtils.dateFromString(date + " " + startTime, DateUtils.YYYYMMDD_HHMM);
		Integer courseTime = getParaToInt("courseTime", 60);
		Date end = new DateTime(start).plusMinutes(courseTime).toDate();
		Long schoolId = getParaToLong("schoolId");
		DkArrange arrange;
		if (arrangeId == null) {
			arrange = new DkArrange();
			arrange.save();
		} else {
			arrange = DkArrange.dao.findById(arrangeId);
		}
		if (schoolId != null) {
			arrange.setSchoolId(schoolId);
		}
		String topic = getPara("topic");
		Integer limit = getParaToInt("limit", 0);
		String classroom = getPara("classroom");
		Integer isHide = getParaToInt("isHide", 0);
		arrange.setTopic(topic);
		arrange.setStartTime(start);
		arrange.setEndTime(end);
		arrange.setCourseTime(courseTime);
		arrange.setLimit(limit);
		arrange.setClassroom(classroom);
		arrange.setIsHide(isHide);
		arrange.setCourseName(courseName);
		arrange.setTeacherName(teacherName);
		arrange.update();
		renderSuccess();
	}

	@Override
	public void delete() {
		Long arrangeId = getParaToLong("arrangeId");
		if (arrangeId == null) {
			renderError(403);
			return;
		}
		DkArrange arrange = DkArrange.dao.findById(arrangeId);
		if (arrange == null) {
			renderError(403);
			return;
		}
		arrange.delete();
		renderSuccess();
	}

	public void cancel() {
		Long arrangeId = getParaToLong("arrangeId");
		Long userId = getParaToLong("userId");
		// DkUser user = DkUser.dao.findById(userId);
		DkArrange arrange = DkArrange.dao.findById(arrangeId);
		// Date startTime = arrange.getStartTime();
		// Date now = new Date();
		// Long bet = (startTime.getTime() - now.getTime()) / 1000;
		// if (bet <= 0) {
		// renderMsg("超过取消时间");
		// return;
		// }
		DkArrangeUser arrangeUser = DkArrangeUser.dao.findById(arrangeId, userId);
		if (arrangeUser == null) {
			LogKit.info("取消失败" + arrangeId + "," + userId);
			renderFailure();
			return;
		}
		arrangeUser.setStatus(0);
		arrangeUser.setCancelTime(new Date());
		arrangeUser.update();
		arrange.updateJoinCount();
		renderSuccess();
	}

	public void users() {
		Long arrangeId = getParaToLong("arrangeId");
		if (arrangeId == null) {
			renderError(403);
			return;
		}
		DkArrange arrange = DkArrange.dao.findById(arrangeId);
		if (arrange == null) {
			renderError(403);
			return;
		}
		Kv kv = Kv.by("arrangeId", arrangeId);
		SqlPara sqlPara = db.getSqlPara("DKArrangeUsers", kv);
		List<Record> items = db.find(sqlPara);
		setItems(JsonKit.toJson(items));
		setInfoItem(JsonKit.toJson(arrange));
		render("/dk/admin/arrange/users.html");
	}
}
